"""
数据库模型定义
"""
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Enum, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
import enum

Base = declarative_base()


class LoginType(str, enum.Enum):
    """登录类型枚举"""
    PASSWORD = "password"  # 账号密码登录
    DINGTALK = "dingtalk"  # 钉钉登录


class Role(Base):
    """角色表"""
    __tablename__ = "roles"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    name = Column(String(50), unique=True, nullable=False, comment="角色名称")
    code = Column(String(50), unique=True, nullable=False, index=True, comment="角色代码")
    description = Column(String(500), nullable=True, comment="角色描述")
    
    # 权限相关（可根据需要扩展）
    permissions = Column(String(1000), nullable=True, comment="权限列表（JSON格式）")
    
    # 状态字段
    is_active = Column(Boolean, default=True, comment="是否启用")
    
    # 时间字段
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    
    # 关系映射
    users = relationship("User", back_populates="role")
    
    def __repr__(self):
        return f"<Role(id={self.id}, name={self.name}, code={self.code})>"


class User(Base):
    """用户表"""
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    username = Column(String(50), unique=True, index=True, nullable=False, comment="用户名")
    email = Column(String(100), unique=True, index=True, nullable=True, comment="邮箱")
    phone = Column(String(20), unique=True, index=True, nullable=True, comment="手机号")
    password_hash = Column(String(255), nullable=True, comment="密码哈希")
    
    # 钉钉相关字段
    dingtalk_userid = Column(String(100), unique=True, index=True, nullable=True, comment="钉钉用户ID")
    dingtalk_unionid = Column(String(100), unique=True, index=True, nullable=True, comment="钉钉UnionID")
    dingtalk_openid = Column(String(100), nullable=True, comment="钉钉OpenID")
    
    # 用户信息
    nickname = Column(String(100), nullable=True, comment="昵称")
    avatar = Column(String(500), nullable=True, comment="头像URL")
    
    # 角色外键
    role_id = Column(Integer, ForeignKey("roles.id"), nullable=True, index=True, comment="角色ID")
    
    # 新增: 实名认证标志
    is_verified = Column(Boolean, default=False, comment="是否实名认证")
    
    # 时间字段
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    last_login = Column(DateTime, nullable=True, comment="最后登录时间")
    
    # 关系映射
    role = relationship("Role", back_populates="users")
    
    def __repr__(self):
        return f"<User(id={self.id}, username={self.username}, role_id={self.role_id})>"


class LoginLog(Base):
    """登录日志表"""
    __tablename__ = "login_logs"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    user_id = Column(Integer, index=True, nullable=False, comment="用户ID")
    login_type = Column(Enum(LoginType), nullable=False, comment="登录方式")
    ip_address = Column(String(50), nullable=True, comment="登录IP")
    user_agent = Column(String(500), nullable=True, comment="用户代理")
    login_time = Column(DateTime, default=datetime.now, comment="登录时间")
    is_success = Column(Boolean, default=True, comment="是否成功")
    error_message = Column(String(500), nullable=True, comment="错误信息")
    
    def __repr__(self):
        return f"<LoginLog(id={self.id}, user_id={self.user_id}, login_type={self.login_type})>"


class ResourceType(str, enum.Enum):
    """资源类型"""
    MENU = "menu"      # 菜单
    PAGE = "page"      # 页面
    ACTION = "action"  # 操作


class Resource(Base):
    """系统资源（菜单/页面/操作）"""
    __tablename__ = "resources"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    name = Column(String(100), nullable=False, comment="资源名称")
    code = Column(String(100), unique=True, nullable=False, index=True, comment="资源编码")
    type = Column(String(20), nullable=False, default=ResourceType.MENU.value, comment="资源类型")
    parent_id = Column(Integer, ForeignKey("resources.id"), nullable=True, index=True, comment="父级ID")
    path = Column(String(200), nullable=True, comment="前端路由路径")
    icon = Column(String(100), nullable=True, comment="图标")
    sort = Column(Integer, default=0, comment="排序")
    is_active = Column(Boolean, default=True, comment="是否启用")

    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")

    # 自关联
    children = relationship("Resource", backref="parent", remote_side=[id])

    def __repr__(self):
        return f"<Resource(id={self.id}, name={self.name}, code={self.code})>"


class RoleResource(Base):
    """角色-资源 关联表"""
    __tablename__ = "role_resources"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    role_id = Column(Integer, ForeignKey("roles.id"), nullable=False, index=True)
    resource_id = Column(Integer, ForeignKey("resources.id"), nullable=False, index=True)
    created_at = Column(DateTime, default=datetime.now)


# 新增 实名认证表
class RealNameAuth(Base):
    __tablename__ = "real_name_auth"
    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="用户ID")
    idcard_image_url = Column(String(300), nullable=False, comment="证件图片地址")
    real_name = Column(String(50), nullable=False, comment="真实姓名")
    id_number = Column(String(30), nullable=False, comment="证件号码")
    address = Column(String(200), nullable=True, comment="住址")
    created_at = Column(DateTime, default=datetime.now, comment="认证时间")





